#计算MA均值
import numpy as np
import pandas as pd
from Utils.DataLoaderAndSaver import DataLoaderAndSaver
from Utils.configs import daysBefore1, daysBefore2, yearsBefore


class IncreaseFeatureCalculation:
    def __init__(self,daysBefore1=0,daysBefore2=1,yearsBefore=4):
        #基本的配置信息
        self.increaseDays = [3, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 122, 150, 180, 200, 244, 250, 300, 366]
        self.increaseTable = 'table_increase'
        self.dataLoaderAndSaver = DataLoaderAndSaver(daysBefore1=daysBefore1, daysBefore2=daysBefore2,
                                                     yearsBefore=yearsBefore)
        self.codes = self.dataLoaderAndSaver.allstocks.index
        self.dailyprices = self.dataLoaderAndSaver.dailyprices

    def __calincrease(self,close,previous_close):
        if previous_close is np.nan:
            return np.nan
        if previous_close==0:
            return np.nan
        increase=(close-previous_close)/previous_close*100
        return round(increase,2)

    #计算历史的涨幅
    def calIncrease(self):
        try:
            self.dataLoaderAndSaver.dropTable(self.increaseTable)
        except:
            print('正常删除表格%s' % self.increaseTable)
        print(self.codes)
        count=0
        for code in self.codes:
            try:
                prices = self.dailyprices[self.dailyprices['code'] == code]
                prices=prices[prices['close']!=np.nan]
                prices = prices.sort_values(by='date', ascending=False)
                # print(prices.shape,prices.head(10))
                index=prices['date']
                # print(prices.index)
                close=pd.DataFrame(prices['close'])
                close.index=index
                mas=[close]
                for day in self.increaseDays:
                    shift=pd.DataFrame(prices['close'].shift(-1*day,axis=0))
                    shift.columns=['shift_close']
                    shift.index=index
                    # print(shift.head(10))
                    merge=pd.concat([close,shift],axis=1)
                    # print('merge',merge.columns,merge.head(10))
                    column='increase_'+str(day)
                    merge[column]=merge.apply(lambda x:self.__calincrease(x['close'],x['shift_close']),axis=1)
                    # print('merge', merge.columns, merge.head(10))
                    mas.append(merge[column])
                df=pd.concat(mas,axis=1)
                df.insert(0,'code',code)
                df.insert(0,'date',df.index)
                # df.colums=self.maColumns
                # df=df.dropna()
                print('mergedf:',code,count,df.columns, df.shape,df.head(10))
                # df.columns=self.maColumns
                # print(df.columns,df.shape)
                self.dataLoaderAndSaver.saveData(self.increaseTable,df,if_exists='append')
                count=count+1
            except:
                print(code,'计算失败')
                with open('log/'+self.dataLoaderAndSaver.todayDate+'_increase_fail.txt','a+',encoding='utf8') as f:
                    f.write(code+'\n')
                count = count + 1
                continue

    def calIncreaseDaily(self):
        for code in self.codes:
            prices = self.dailyprices[self.dailyprices['code'] == code]
            prices = prices[prices['close'] != np.nan]
            prices=prices.sort_values(by='date',ascending=False)
            # print(prices.shape,prices.head(10))
            index = prices['date']
            # print(prices.index)
            close = pd.DataFrame(prices['close'])
            close.index = index
            mas = [close]
            for day in self.increaseDays:
                shift = pd.DataFrame(prices['close'].shift(-1 * day, axis=0))
                shift.columns = ['shift_close']
                shift.index = index
                # print(shift.head(10))
                merge = pd.concat([close, shift], axis=1)
                # print('merge',merge.columns,merge.head(10))
                column = 'increase_' + str(day)
                merge[column] = merge.apply(lambda x: self.__calincrease(x['close'], x['shift_close']), axis=1)
                # print('merge', merge.columns, merge.head(10))
                mas.append(merge[column])
            df = pd.concat(mas, axis=1)
            df.insert(0, 'code', code)
            df.insert(0, 'date', df.index)
            # df.colums=self.maColumns
            df = df.dropna()
            print('mergedf:', df.columns, df.shape, df.tail(10))
            # df.columns=self.maColumns
            # print(df.columns,df.shape)
            self.dataLoaderAndSaver.saveData(self.increaseTable, df, if_exists='append')

ifc=IncreaseFeatureCalculation(daysBefore1=daysBefore1,daysBefore2=daysBefore2,yearsBefore=yearsBefore)
ifc.calIncrease()

